#include <string.h>
#include <thread>
#include "XTcp.h"

class TcpThread {
public:
	void Main() {
		char buf[1024] = { 0 };
		int i = 0;
		for (;;) {
			int recvlen = client.Recv(buf, sizeof(buf)-1);
			printf("recvlen=%d\n", recvlen);			
			if (recvlen <= 0) break;
			buf[recvlen] = 0;//°üo?\r??3μ,\n??DD·￠?í123￡??òê?μ?5??×??ú￡?buf[5]=0;
			if (strstr(buf, "quit") != NULL) {
				char re[] = "quit success\n";
				client.Send(re, strlen(re) + 1);
				break;
			}
			printf("recv:%s\n", buf);
			for (i = 0; i <= recvlen ; i++) {
				printf("buf[%d]=[%d] ", i, buf[i]);
			}
			printf("\n");
			int sendlen = client.Send("Ok\n", 4);
		}
		client.Close();
		delete this;
	}
	XTcp client;
};
#include <sys/epoll.h>
int main(int argc, char *argv[]) {
	unsigned short port = 8099;
	if (argc>1) {
		port = atoi(argv[1]);
	}
	XTcp server;//·t???÷
	server.CreateSocket();
	server.Bind(port);
	//è?1?acceptμ￥??3ì′|àí?ò
	//create epoll
	int epfd = epoll_create(256);//创建一个epoll，最多放256套接字
	epoll_event ev;
	ev.data.fd = server.sock;
	ev.events = EPOLLIN | EPOLLET;//边缘触发，高效方式
	epoll_ctl(epfd,EPOLL_CTL_ADD,server.sock,&ev);//注册到epoll中
	epoll_event event[20];
	char buf[1024]={0};
	const char *msg = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nLu";
	int size = strlen(msg);
	server.SetBlock(false);//设置非阻塞
	for (;;) {
		int count =epoll_wait(epfd,event,20,500);//500ms为超时时间
		if(count<=0) continue;
		for(int i=0;i<count;i++){
			if(event[i].data.fd == server.sock){//监听端口socket
				for(;;){
					XTcp client = server.Accept();
					if(client.sock<=0){
						break;
					}
					ev.data.fd = client.sock;
					ev.events = EPOLLIN | EPOLLET;
					epoll_ctl(epfd,EPOLL_CTL_ADD,client.sock,&ev);
				}
			
			}
			else{
				XTcp client;
				client.sock = event[i].data.fd;
				client.Recv(buf,1024);
				client.Send(msg,size);
				epoll_ctl(epfd,EPOLL_CTL_DEL,client.sock,&ev);
				client.Close();
			}
		}
		// XTcp client = server.Accept();//?í?§??
		// TcpThread *th = new TcpThread();
		// th->client = client;
		// std::thread sth(&TcpThread::Main, th);
		// sth.detach();//??3ì·?à?
	}
	server.Close();
	getchar();
	return 0;
}
